#include "Common.h"
#include "LocalPlayer.h"
#include "PhysicsSystem.h"
#include "PlayerController.h"

LocalPlayer::LocalPlayer()
	: mMoveDir(0)
	, mVelocity(0)
	, mController(NULL)
{
	mMoveSpeed = 400.0f;
	mBoundRadius = 25.0f;
	mBoundHeight = 180.0f;
}

LocalPlayer::~LocalPlayer()
{
	SAFE_DELETE(mController);
}

void LocalPlayer::Update(float elapsedTime)
{
	Player::Update(elapsedTime);

	Move(elapsedTime);
}

void LocalPlayer::AddToMap(Scene* scene)
{
	Player::AddToMap(scene);
	
	mController = new PlayerController(scene, getPosition(), mBoundRadius, mBoundHeight);
}

void LocalPlayer::RemoveFromMap()
{
	SAFE_DELETE(mController);

	Player::RemoveFromMap();
}

void LocalPlayer::Rotate(float x, float y)
{
	mRotation.X += Math::Trunc(x);
	mRotation.Z += Math::Trunc(y);
}

void LocalPlayer::setPosition(const Vector3& v)
{
	Player::setPosition(v);

	if (mController)
		mController->SetPosition(v);
}

void LocalPlayer::SetMoveDir(const Vector3& dir)
{
	if (dir.IsZero())
	{
		if (mState == ES_Moving)
			mState = ES_Falling;
	}
	else
	{
		mState = ES_Moving;
	}

	mMoveDir = mRotation.Quat() * dir;
	mMoveDir.Normalize();
}

void LocalPlayer::Jump()
{
	if (mVelocity.Y == 0)
		mVelocity.Y = 400.0f;
}

void LocalPlayer::Move(float elapsedTime)
{
	if (mState == ES_Idle && mMoveDir.IsZero())
		return;

	// update the falling velocity.
	float fallingDist = mVelocity.Y * elapsedTime + DEFAULT_GRAVITY * Square(elapsedTime) * 0.5f;
	mVelocity.Y += DEFAULT_GRAVITY * elapsedTime;

	// move the controller.
	Vector3 translate = mMoveDir * mMoveSpeed;
	translate.Y += fallingDist;
	mController->Move(translate);

	mPosition = mController->GetPosition();
}
